﻿/*
=======================================================
    MHCheck【检测报告】
=======================================================
*/

using Entities;
using Microsoft.AspNetCore.Mvc;

namespace Services
{
    public interface IMHCheckRepository : IRepository<MHCheck>
    {
        Task<long?> GetLastCheckTime(int deviceId);
        Task<Dictionary<int, MHCheck>> GetLatestMHChecks(List<int> mhIds);
    }

    public class MHCheckRepository : BaseRepository<MHCheck>, IMHCheckRepository
    {
        public MHCheckRepository(ISqlSugarClient dB, ICurrentUser currentUser, IQuery<MHCheck> query)
            : base(dB, currentUser, query)
        {
        }
        public async Task<long?> GetLastCheckTime(int deviceId)
        {
            var groupInfoId = _currentUser.CurrentUserInfo.LoginTypeID;
            var mhId = await _DB.Queryable<MagnetHead>()
                .Where(m => m.DeviceID == deviceId && m.GroupInfoID == groupInfoId)
                .Select(m => m.MHID)
                .FirstAsync();
            return await _DB.Queryable<MHCheck>()
               .Where(m => m.MHID == mhId && m.GroupInfoID == groupInfoId)
               .MaxAsync(m => m.CheckTime);
        }

        public override int BatchInsert(List<MHCheck> entities)
        {
            try
            {
                _DB.Ado.BeginTran();
                // 提取所有需要查询的 GroupInfoID 和 DeviceID 组合
                var groupInfoID = _currentUser.CurrentUserInfo.LoginTypeID;
                var groupDevicePairs = entities.Select(e => new { groupInfoID, e.DeviceID }).Distinct().ToList();

                // 批量查询对应的 MHID
                var mhIdMapping = _DB.Queryable<MagnetHead>()
                                     .Where(m => groupDevicePairs.Any(p => groupInfoID == m.GroupInfoID && p.DeviceID == m.DeviceID))
                                     .Select(m => new { m.GroupInfoID, m.DeviceID, m.MHID })
                                     .ToList()
                                     .ToDictionary(k => (k.GroupInfoID, k.DeviceID), v => v.MHID);

                foreach (var entity in entities)
                {
                    var key = (groupInfoID, entity.DeviceID);
                    if (!mhIdMapping.TryGetValue(key, out var mhId))
                    {
                        throw new CustomException($"未找到 GroupInfoID: {entity.GroupInfoID} 和 DeviceID: {entity.DeviceID} 对应的 MHID。");
                    }
                    entity.MHID = mhId;
                }

                // 调用基类的批量插入方法
                var result = base.BatchInsert(entities);
                _DB.Ado.CommitTran();
                return result;
            }
            catch (Exception ex)
            {
                _DB.Ado.RollbackTran();
                throw new CustomException($"批量插入数据时发生错误: {ex.Message}", 2, ex);
            }
        }

         public async Task<Dictionary<int, MHCheck>> GetLatestMHChecks(List<int> mhIds)
        {
            // 批量查询所有相关记录
            var allChecks = await _query.GetQueryable()
                .Where(x => mhIds.Contains(x.MHID))
                .ToListAsync();

            // 内存中分组并获取每个MHID的最新记录
            return allChecks
                .GroupBy(x => x.MHID)
                .ToDictionary(
                    g => g.Key,
                    g => g.OrderByDescending(x => x.CheckTime).FirstOrDefault());
        }
    }
}
